<template>
  <div class="app-container">
    <div :class="{ hidden: isHidden }">
      <el-row class="paragraph_spacing">
        <div class="clearfix">
          <div class="left" style="position: relative; width: 100px; float: left;">
            <!-- 加载动画 -->
            <div v-if="isIconLoading">
              <el-loading></el-loading>
            </div>
            <!-- 图标 -->
            <img
              ref="iconImg"
              alt="元芳"
              class="app-image"
              style="width: 100%; height: auto; cursor: pointer;"
              @click="triggerFileInput"
              @load="onIconImageLoad"
              src=""
              :class="{ 'hidden': isIconLoading }"
            >
            <!-- 隐藏的文件输入框 -->
            <input
              ref="fileInput"
              type="file"
              style="display: none;"
              :accept="'.jpg,.png,.gif,.jpeg'"
              @change="uploadAppIcon"
            >
          </div>

          <!--项目简介-->
          <div class="left" style="width:85%;height: fit-content;float:none;margin-left: 120px">
            <p class="large">
              <span style="margin-right: 10px;">{{ appDetail.app_name }}</span>
              <!-- <el-tag style="margin-right: 10px" :type="appDetail.status | statusFilter" @click="refreshStatus">
                {{ appDetail.status }}
              </el-tag> -->
              <!-- <i style="vertical-align: -3px; color: #606266" class="el-icon-refresh-right" @click="refreshStatus" /> -->
            </p>
            <span class="base">{{ appDetail.app_description }}</span><br>
            <!--          <span class="base">{{ $t('namespace') }}：{{ projectDetail.namespace }}</span><br>-->
            <br>
            <!-- 展示应用的开发者 -->
            <span class="base">{{ $t('developer')+ ': ' + creator_name }}</span><br>
            <!-- <span class="base">{{ $t('original_problem') + ': ' + (typeof appDetail.app_requirement === 'undefined' ? '' : appDetail.app_requirement) }}</span><br>-->
            <span class="base">{{ $t('creation_time') + ': ' + stringToDate(appDetail.created_time) }}</span><br>
            <span class="base">{{ $t('update_time') + ': ' + stringToDate(appDetail.update_time) }}</span><br>
            <!--<span class="base">{{ $t('create') }}{{ $t('time') }}：{{ appDetail.createTime }}</span>-->
            <!-- <div class="base">
              NodePort： <br>
              <div v-for="(service, idx) in serviceList">
                {{(idx + 1) + ". " + service["name"]}}<br>
                <span><div  v-for="port in service['ports']">&emsp;&emsp;&emsp;{{ "- " + port["name"]}}:{{ port["nodePort"]}}</div></span>
              </div>
            </div> -->
          </div>
        </div>
      </el-row>

      <el-row type="flex" justify="space-between" class="row_spacing">
        <el-col :span="12">
          <el-radio-group v-model="radio">
            <el-radio-button id="1" :label="$t('description')" />
            <el-radio-button id="5" ref="appScriptRadioButton" :label="$t('appScript')" />
            <el-radio-button v-if="ableToChange && statusIsStop && appDetail.status!=='Running'" id="2" :label="$t('config')" />
            <el-radio-button id="3" :label="$t('log')" />
            <el-radio-button v-if="showExecutor" id="4" :label="$t('executor')" />
            <!--<el-radio-button v-if="$store.getters.prometheus_prefix_available" id="5" :label="$t('status')"/>-->
            <!--<el-radio-button v-if="$store.getters.loki_getlog_available" id="6" :label="$t('log')"/>-->
          </el-radio-group>
        </el-col>
        <el-col :span="20" class="clearfix">
          <el-button-group class="right">
            <!--<el-button icon="el-icon-warning-outline" :disabled="appDetail.status==='STOP'" @click="stopProject">
              {{ $t('stop') }}
            </el-button>
            <el-button icon="el-icon-refresh" @click="restart">{{ $t('restart') }}</el-button>
            <el-button icon="el-icon-edit" @click="edit">{{ $t('edit') }}</el-button>-->
            <el-button
              icon="el-icon-edit"
              @click="editProject"
            > {{ $t('edit') }}
            </el-button>
            <el-button
              icon="el-icon-delete"
              @click="deleteProject"
            > {{ $t('delete') }}
            </el-button>
            <el-button
              icon="el-icon-upload"
              @click="publishAppVisible = true"
            > {{ $t('publish') }}
            </el-button>
<!--            <el-button-->
<!--              icon="el-icon-video-play"-->
<!--              @click="startDeveloper"-->
<!--            > {{ $t('debugging') }}-->
<!--            </el-button>-->
            <el-button
              type="primary"
              icon="el-icon-switch-button"
              @click="startUser"
            > {{ $t('startover') }}
            </el-button>
          </el-button-group>
        </el-col>
      </el-row>

      <div v-if="showDescription" style="background-color: white;padding: 20px 20px;">
        <el-form ref="appDetail" :model="appDetail" label-width="90px" style="width: 90%;">
          <el-form-item :label="$t('original_problem')">
            <el-input v-model="appDetail.app_requirement" />
          </el-form-item>
          <el-form-item :label="$t('name')">
            <el-input v-model="appDetail.app_name" />
          </el-form-item>
          <el-form-item :label="$t('description')">
            <el-input v-model="appDetail.app_description" type="textarea" :rows="7" />
          </el-form-item>
          <el-form-item>
            <a href="#" class="llm-link" @click="llmRecommended">智能推荐应用名称和描述</a>
          </el-form-item>
          <el-form-item :label="$t('no_authentication_access')">
            <el-checkbox v-model="appDetail.app_no_authentication_access">
              {{ $t('allow_use_without_login') }}
            </el-checkbox>
          </el-form-item>
          <el-form-item :label="$t('api_model')">
            <el-checkbox v-model="appDetail.api_model_enable">
              {{ $t('allow_third_party_api_access_description') }}
            </el-checkbox>
          </el-form-item>
          <el-form-item v-if="appDetail.api_model_enable" :label="$t('api_description')">
            <el-input v-model="appDetail.api_model_description" type="textarea" :rows="7" />
          </el-form-item>

          <el-form-item>
            <!--            <el-link v-if="appDetail.app_api_model.api_enable" :underline="false" @click="showApiLocationDialog = true">-->
            <!--              {{ $t('view_api_test_url') }}-->
            <!--            </el-link>-->
            <a v-if="appDetail.api_model_enable" href="#" class="llm-link" :underline="false" @click="showApiLocationDialog = true">
              {{ $t('view_api_test_url') }}
            </a>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="toSaveApp">{{ $t('save') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="showConfig">
        <detail-config v-if="statusIsStop && appDetail.status!=='Running'" :app-name="appDetail.app_id" :app-description="appDetail.app_name" :task-list="appDetail.task_list" />
      </div>
      <div v-if="showLog">

        <detail-log :app-i-d="appID" />
      </div>

      <div v-if="showAppScript" style="background-color: white;padding: 20px 20px;">
        <el-form label-width="80px" style="width: 90%;">
          <div style="margin-bottom: 20px">
            <json_code v-model="appScript" />
          </div>

          <el-button type="primary" @click="SaveAppScript">{{ $t('save') }}</el-button>

        </el-form>

      </div>
      <div v-if="showExecutor">
        <start-executing ref="executor" :app-id="appDetail.app_id" />
      </div>
      <!--<div id="div4" class="white hidden">
        这是service
      </div>
      <!-<div id="div5" class="white app-container" style="border-radius: 3px;" v-if="showStatus">->
      <div v-if="showStatus" id="div5">
        这是日志
      </div>
      <div id="div6" class="hidden">
        这是状态
      </div>-->
    </div>
    <div :class="{ hidden: !isHidden }">
      <router-view />
    </div>
    <!-- 确认发布的对话框 -->
    <el-dialog destroy-on-close :visible.sync="publishAppVisible" :title="$t('appRelease')" width="45%">
      <publish-app ref="publish-app" style="display: block; margin-left: 3%;" :app_id="appDetail.id" :app_name="appDetail.app_name" :app_description="appDetail.app_description" />
      <span slot="footer">
        <el-button @click="publishAppVisible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="$refs['publish-app'].publishApp(appDetail);publishAppVisible = false">{{ $t('publish') }}</el-button>
      </span>
    </el-dialog>

    <!--    <el-dialog destroy-on-close :visible.sync="showApiLocationDialog" :title="$t('api_test_url')" width="45%">-->
    <!--      &lt;!&ndash; 放置浮窗内容，例如API接口测试地址 &ndash;&gt;-->
    <!--      <p class="bold-text">{{ $t('api_test_content') }}</p>-->
    <!--      <p>{{ api_test_url }}</p>-->
    <!--      <span slot="footer" class="dialog-footer">-->
    <!--        <el-button type="primary" @click="showApiLocationDialog = false">{{ $t('confirm') }}</el-button>-->
    <!--      </span>-->

    <el-dialog
      :title="$t('api_test_url')"
      :visible.sync="showApiLocationDialog"
      width="50%"
      :close-on-click-modal="false"
      destroy-on-close
      @close="handleClose"
    >
      <el-form ref="form" label-width="120px">
        <el-form-item :label="'header'">
          <el-input
            v-model="api_header"
            style="width: 80%"
            type="textarea"
            :rows="1"
          />
        </el-form-item>

        <el-form-item :label="'body'">
          <el-input
            v-model="api_body"
            style="width: 80%"
            type="textarea"
            :rows="5"
          />
        </el-form-item>

      </el-form>

      <div class="btn_center">
        <el-button type="primary" @click="testAPI">测试</el-button>
      </div>

      <api-test title="接口返回值" :task_result="taskRunResult" />
    </el-dialog>

    <el-dialog :visible.sync="showRecommendDialog" title="智能推荐应用的名称和描述" width="50%">
      <el-form label-width="120px">
        <el-form-item :label="$t('appName')">
          <el-input v-model="appDetail.app_name" disabled />
        </el-form-item>
        <el-form-item :label="$t('appDescription')">
          <el-input v-model="appDetail.app_description" type="textarea" :rows="5" disabled />
        </el-form-item>
        <el-form-item>
          <template #label>
            {{ $t('appName') }}<br>({{ $t('recommended') }})
          </template>
          <el-input v-model="recommendedName" :placeholder="$t('recommending')" />
        </el-form-item>
        <el-form-item>
          <template #label>
            {{ $t('appDescription') }}<br>({{ $t('recommended') }})
          </template>
          <el-input v-model="recommendedDescription" :placeholder="$t('recommending')" type="textarea" :rows="5" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRecommendDialog = false">关闭</el-button>
        <el-button type="primary" @click="applyRecommendations">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import detailConfig from './components/detailConfig.vue'
import detailLog from './components/detailLog.vue'
import startExecuting from './components/startExecuting.vue'
import publishApp from './components/publishApp.vue'
import '@/styles/common.css'
import { deleteApp, generateAppInfo, getAppById, updateBasicApp } from '@/api/app'
import JsonCodeMirror from '@/components/JavascriptCodemirror/index.vue'
import JsonEditor from 'vue-json-editor'
import { updateApp, uploadAppIcon, getIconByAppId } from '@/api/app'
import { searchGlobalSettings } from '@/api/globalSetting'
import apiTest from './components/taskRun.vue'
import { app_api } from '@/api/executor'
import { getUserName } from '@/api/user'

export default {
  name: 'ContainerDetail',
  // eslint-disable-next-line vue/no-unused-components
  components: { detailConfig, detailLog, startExecuting, publishApp: publishApp, json_code: JsonCodeMirror, JsonEditor, apiTest },
  data() {
    return {
      radio: '',
      appID: '',
      appDetail: {},
      serviceList: [],
      ableToChange: false,
      publishAppVisible: false,
      approvalAppVisible: false,
      creator_name: '', // 用户名称
      showStatus: false, // 用于解决状态曲线图宽度为100px
      statusIsStop: true, // 控制删除键是否可用,
      isHidden: false, // 用于三级路由
      appScript: null, // 应用脚本
      showApiLocationDialog: false, // 展示API地址
      base_url: '',
      api_test_url: 'http://yf.free4inno.com/#/app_management/index/details/?id=[id]&cityName=[cityName]\n',
      api_body: '',
      api_header: '',
      taskRunResult: {},

      // 上传应用图标
      selectedUploadFile: null, // 是一个file类型的文件对象，用于保存图片文件的信息，发送到后端
      imageUrl: null, // 是图片的URL地址，用于回显图片
      // 应用图标展示
      isIconLoading: true, // 控制加载动画的显示与隐藏
      showRecommendDialog: false, // 控制推荐浮窗显示
      recommendedName: '', // 智能推荐的应用名称
      recommendedDescription: '' // 智能推荐的应用描述
    }
  },
  computed: {
    showDescription: function() {
      return (this.radio === this.$t('description'))
    },
    showAppScript: function() {
      return (this.radio === this.$t('appScript'))
    },
    showConfig: function() {
      return (this.radio === this.$t('config'))
    },
    showLog: function() {
      return (this.radio === this.$t('log'))
    },
    showExecutor: function() {
      return (this.radio === this.$t('executor'))
    }
  },
  created() {
    const id = this.$route.query.id
    this.appID = this.$route.query.id
    const radioTest = this.$route.query.radio
    // 检查路由参数中是否包含 'radio' 参数
    if (radioTest) {
      this.radio = this.$t('log')
    } else {
      this.radio = this.$t('description')
    }

    if (id) {
      this.$store.commit('application/CHANGE_APPDETAILID', id)
    } else {
      this.appID = Number(this.$store.getters.appDetailId)
    }
    if (this.$route.path !== '/app_management/index/details/' && this.$route.path !== '/app_management/index/details') this.isHidden = true
    this.fetchData()
  },
  methods: {
    async fetchData() {
      await getAppById(this.appID).then(response => {
        const data = response
        console.log('应用详情页面的应用详情：', response)
        this.appDetail = data
        this.appScript = JSON.stringify(JSON.parse(this.appDetail.script), null, 2)
        if (data.creator_id !== this.$store.getters.id && !this.$store.getters.isAdmin()) {
          this.$message({
            type: 'error',
            message: '您没有权限访问此页面'
          })
          this.$router.push('/')
          return
        }
        /* this.$message({
          message: '获取成功',
          type: 'success'
        }) */
      }).catch(error => {
        console.log(error)
        this.$message({
          message: '获取失败',
          type: 'error'
        })
      })

      const [name, data] = await Promise.all([getUserName(this.appDetail.creator_id),
        searchGlobalSettings({ 'searchVal': '', 'region': 'studio_url' })]).catch(error => {
        console.log(error)
        this.$message({
          message: '获取失败',
          type: 'error'
        })
      })
      this.creator_name = name.message
      this.base_url = data[0].value
      this.api_test_url = this.base_url + '/app_api/' + this.appID
      console.log(this.base_url)
      await this.loadIcon()
    },
    refreshStatus() {
      this.fetchData()
      this.$refs.child_1.fetchData()
      this.$message({
        message: this.$t('refresh_tips'),
        type: 'success'
      })
    },
    startUser() {
      /* this.$confirm(this.$t('container_start_tips'), this.$t('tip'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        this.$message({
          message: this.$t('container_starting_tips'),
          type: 'success'
        })
        start({ 'id': this.$route.params.id }).then(response => {
          this.fetchData()
          this.$refs.child_1.fetchData()
        })
      })*/
      // 启动成功,输出信息并设定状态
      this.$message({
        message: this.$t('container_starting_tips'),
        type: 'success'
      })
      this.appDetail.status = 'Running'
      this.statusIsStop = false
      this.ableToChange = false
      // 启动成功 切换到执行界面
      // this.showExecutor = true
      // this.radio = this.$t('executor')
      // 切换到日志界面
      // this.radio = this.$t('log')
      this.$router.push({ path: `/app_management/index/details/chatExecutingUser`, query: { id: this.appID }})
    },
    startDeveloper() {
      // 启动成功,输出信息并设定状态
      this.$message({
        message: this.$t('container_starting_tips'),
        type: 'success'
      })
      this.appDetail.status = 'Running'
      this.statusIsStop = false
      this.ableToChange = false
      this.$router.push({ path: `/app_management/index/details/chatExecutingDeveloper`, query: { id: this.appID }})
    },
    edit() {
      this.ableToChange = true
      this.radio = this.$t('config')
    },
    deleteProject() {
      this.$confirm(this.$t('workflow_delete_tips'), this.$t('tip'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
      // 删除该应用
        deleteApp(this.appID).then(response => {
          console.log('删除方法执行了')
          console.log(response)
          this.$message({
            message: this.$t('delete_success_tips'),
            type: 'success'
          })
          // this.freshList(1)
          // 路由至应用管理页面
          this.$router.push({ path: '/app_management/index' })
        }).catch(error => {
          console.log(error)
          this.$message({
            message: this.$t('delete_error_tips'),
            type: 'error'
          })
        })
      }).catch(() => {
        this.$message({
          message: this.$t('delete_cancel_tips'),
          type: 'info'
        })
      })
    },
    editProject() {
      this.$router.push({ path: '/app_management/index/details/edit', query: { id: this.appID }})
    },
    // 保存编辑app名称和描述的表单
    toSaveApp() {
      // const api_model = {
      //   api_enable: this.appDetail.app_api_model.api_enable === true ? this.appDetail.app_api_model.api_enable : false,
      //   api_description: this.appDetail.app_api_model.api_enable === true ? this.appDetail.app_api_model.api_description : ''
      // }
      const basic = {
        id: this.appDetail.id,
        app_name: this.appDetail.app_name,
        app_description: this.appDetail.app_description,
        app_no_authentication_access: this.appDetail.app_no_authentication_access === true ? this.appDetail.app_no_authentication_access : false,
        api_model_enable: this.appDetail.api_model_enable === true ? this.appDetail.api_model_enable : false,
        api_model_description: this.appDetail.api_model_enable === true ? this.appDetail.api_model_description : '',
        // app_api_model: api_model,
        app_requirement: this.appDetail.app_requirement
      }
      updateBasicApp(basic).then(response => {
        this.$message({
          message: this.$t('application_updated_success_tips'),
          type: 'success'
        })
        // this.$router.go(0) // 重新加载当前页面
      }).catch(err => {
        console.log('更新应用基本信息出错', err)
      })
    },
    // 保存appScript
    SaveAppScript() {
      this.$confirm(this.$t('save_appScript_tips'), this.$t('tip'), {
        confirmButtonText: this.$t('confirm'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        const data = {
          'id': this.appID,
          'script': JSON.parse(this.appScript)
        }
        updateApp(data).then(() => {
          this.$message({
            message: this.$t('appScript_updated_success_tips'),
            type: 'success'
          })
        }).catch(err => {
          console.log('确认修改应用脚本失败', err)
        })
      }).catch(() => {
        this.$message({
          message: this.$t('save_appScript_cancel_tips'),
          type: 'info'
        })
      })
    },
    // 将Wed, 28 Aug 2024 19:59:45 GMT字符串，转换为2024-08-28 19:59:45
    stringToDate(dateString) {
      if (typeof dateString !== 'string') {
        // 创建 Date 对象
        const date = new Date(dateString['$date'])

        // 获取年份
        const year = date.getUTCFullYear()
        // 获取月份，注意要加 1，因为月份是从 0 开始的
        const month = String(date.getUTCMonth() + 1).padStart(2, '0')
        // 获取日期
        const day = String(date.getUTCDate()).padStart(2, '0')
        // 获取小时
        const hours = String(date.getUTCHours()).padStart(2, '0')
        // 获取分钟
        const minutes = String(date.getUTCMinutes()).padStart(2, '0')
        // 获取秒
        const seconds = String(date.getUTCSeconds()).padStart(2, '0')

        // 组合成指定格式的字符串
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      }
      // 正则表达式来匹配日期和时间的各个部分
      const regex = /^(\w+),\s+(\d+)\s+(\w+)\s+(\d+)\s+(\d{2}):(\d{2}):(\d{2})\s+GMT$/
      const parts = dateString.match(regex)

      if (!parts) {
        throw new Error('Invalid date string format')
      }

      // 从匹配结果中提取年、月、日等
      const [, , day, monthShort, year, hour, minute, second] = parts

      // 映射月份缩写到数字（注意月份是从0开始的）
      const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
      const monthIndex = months.indexOf(monthShort)
      if (monthIndex === -1) {
        throw new Error('Invalid month in date string')
      }

      // 创建一个新的Date对象
      const date = new Date(Date.UTC(year, monthIndex, day, hour, minute, second))

      // 格式化日期时间为YYYY-MM-DD HH:MM:SS
      const formattedDate = `${date.getUTCFullYear()}-${(date.getUTCMonth() + 1).toString().padStart(2, '0')}-${date.getUTCDate().toString().padStart(2, '0')} ${date.getUTCHours().toString().padStart(2, '0')}:${date.getUTCMinutes().toString().padStart(2, '0')}:${date.getUTCSeconds().toString().padStart(2, '0')}`

      return formattedDate
    },
    // 取图片 Id
    getImageId(appName) {
      if (!appName || appName.length === 0) return 0
      const firstChar = appName[0].toUpperCase() // 取应用名称的首字母并转为大写
      const charCode = firstChar.charCodeAt(0) // 转换为字符编码
      return charCode % 20 // 对20取模，得到0-19
    },
    // 获取图片URL
    // getImageUrl(appName) {
    //   const imageId = this.getImageId(appName)
    //   return require(`@/assets/icons/${imageId}.png`)
    // },
    // getImageUrl() {
    //   return getIconByAppId(this.appID)
    // },
    testAPI() {
      const id = this.appID
      app_api(id, this.api_body).then(res => {
        console.log('获取到的api测试结果:', res)
        this.taskRunResult = res
      }).catch(error => {
        console.log('执行API出错:', error)
      })
    },
    handleClose() {
      // 初始化api_body, api_header和taskRunResult
      this.api_body = ''
      this.api_header = ''
      this.taskRunResult = {}
    },
    // 根据设置好的大模型提示词让大模型生成应用名称和描述
    llmRecommended(event) {
      event.preventDefault() // 阻止默认的链接跳转行为
      this.recommendedName = ''
      this.recommendedDescription = ''
      this.showRecommendDialog = true // 显示浮窗
      // 获取设置中应用信息的提示词
      const data = {
        original_name: this.appDetail.app_name,
        original_description: this.appDetail.app_description,
        instruction: this.appDetail.app_requirement
      }

      generateAppInfo(data)
        .then(res => {
          // console.log('获取到的推荐', res)
          this.recommendedName = res.name
          this.recommendedDescription = res.description
        })
        .catch(err => {
          console.log('获取大模型生成的应用信息出错：', err)
        })
    },
    applyRecommendations() {
      this.appDetail.app_name = this.recommendedName
      this.appDetail.app_description = this.recommendedDescription
      this.showRecommendDialog = false
    },
    // /////////////////////// image upload ////////////////////////////////
    // 触发文件选择器
    triggerFileInput() {
      this.$refs.fileInput.click() // 触发隐藏的文件输入框
    },
    uploadAppIcon(event) {
      this.selectedUploadFile = event.target.files[0]
      this.imageUrl = URL.createObjectURL(this.selectedUploadFile)

      // 将数据提交到后台
      const maxFileSize = 2 * 1024 * 1024

      if (this.selectedUploadFile.size > maxFileSize) { // 校验文件大小
        this.$message.error(`图片大小不能超过 ${maxFileSize / 1024 / 1024} MB`)
        return
      }

      if (!this.selectedUploadFile.type.startsWith('image/')) { // 检查是否是图片类型
        this.$message.error(this.$t('only_image_allowed'))
        return
      }

      // 创建 FormData 对象
      const formData = new FormData()
      formData.append('icon', this.selectedUploadFile) // 将文件添加到 FormData 中

      // 向后端发送请求 调用上传头像的 API
      uploadAppIcon(formData, this.appID)
        .then(response => {
          if (response.message === 'success') {
            this.$message.success('应用图标上传成功')
            // 刷新页面
            this.loadIcon()
          } else {
            this.$message.error('应用图标上传失败，请重试')
          }
        })
        .catch(error => {
          this.$message.error('应用图标上传失败，请检查网络或联系管理员')
          console.error('上传错误:', error)
        })
    },
    async loadIcon() {
      try {
        const response = await getIconByAppId(this.appID)
        if (response.type.startsWith('image/')) {
          // 创建一个指向 Blob 对象的 URL
          const url = URL.createObjectURL(response)
          this.$refs.iconImg.src = url
        } else {
          this.$refs.iconImg.src = require(`@/assets/icons/0.png`)
        }
      } catch (error) {
        this.$refs.iconImg.src = require(`@/assets/icons/0.png`)
      }
    },
    onIconImageLoad() {
      this.isIconLoading = false // 当图片加载完成后隐藏加载动画
    }
  }
}
</script>

<style scoped>
.app-container{
    padding: 20px;
}
.paragraph_spacing{
  margin-bottom: 20px;
}
.app-image {
  width: 100px;
  height: 100px;
  border-radius: 25%;
  overflow: hidden;
}
.bold-text {
  font-weight: bold;
}
.btn_center {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
